package com.example.springboot.service;

import com.example.springboot.Dao.UserRepository;
import com.example.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserRepository userRepository;

    //@CachePut缓存新增或更新的数据到缓存，其缓存的名称为user,数据的key是user的account
    @CachePut(value = "user",key = "#user.account")
    public User save(User user){
      User user1 =   userRepository.save(user);
      System.out.println("为id和Key为："+user1.getAccount()+"做了缓存");
      return user1;
    }

    //@Cacheable缓存key为user的uid数据到缓存user中
    @Cacheable(value = "user",key = "#user.uid")
    public User findOne(User user){
        User user2 = userRepository.findByUid(user.getUid());
        System.out.println("为id和Key为："+ user2.getUid()+"做了缓存");
        return user2;
    }

    //@CacheEvict删除缓存中value为user的缓存
    @CacheEvict(value = "user")
    public void deleteUserByUid(Integer acocunt){
        userRepository.deleteByAccount(acocunt);
        System.out.println("删除id,key了为："+acocunt+"做了缓存");
    }

}
